package com.boot;

import java.util.concurrent.ConcurrentHashMap;

public class ObjectPool<T> {
    private final ConcurrentHashMap<T, Boolean> pool = new ConcurrentHashMap<>();

    //借出对象
    public T borrowObject() {
        return pool.keySet().stream()
                .filter(obj -> pool.replace(obj, true, false))
                .findFirst().orElse(null);
    }

    //归还对象
    public void returnObject(T obj) {
        pool.replace(obj, false, true);
    }

    //添加对象
    public void addObject(T obj) {
        pool.put(obj, true);
    }

    public static void main(String[] args) {
        ObjectPool<String> pool = new ObjectPool<>();
        pool.addObject("Resource1");
        pool.addObject("Resource2");
        pool.addObject("Resource3");

        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                String source = pool.borrowObject();
                if (source != null) {
                    System.out.println(Thread.currentThread().getName() + " 获取到资源: " + source);
                    try {
                        Thread.sleep(1000); //模拟使用资源
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                    pool.returnObject(source);
                    System.out.println(Thread.currentThread().getName() + " 归还资源: " + source);
                } else {
                    System.out.println(Thread.currentThread().getName() + " 未获取到资源");
                }
            }).start();
        }
    }
}
